/*
 * Created on Feb 17, 2005
 */
package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Location;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.finance.openpo.forms.OpenPurchaseOrderForm;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;

/**
 * @author Ravikanth
**/
public class OpenPurchaseOrderNewCommand extends ActionCommand
{
	public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws ScalarException
	{
		HashMap errors			= new HashMap();
		HashMap info            = new HashMap();
		String actionForward 	= "openPurchaseOrder";
		String action   		= request.getParameter( REQUEST_ACTION );
		HttpSession mSession 	= request.getSession();
		OpenPurchaseOrderForm purchaseOrderForm = ( OpenPurchaseOrderForm ) form;

		try
		{
			if( ACTION_NEW.equalsIgnoreCase( action ) )
			{
				resetPurchaseOrderForm( purchaseOrderForm );
				purchaseOrderForm.setPoNumber( PurchaseOrderDAO.loadAutomatedPurchaseOrderNo () );
				purchaseOrderForm.setPoDate( StringUtils.formatDateToString( new Date( System.currentTimeMillis() ) ) );
				purchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
				purchaseOrderForm.setBillingAddress_id( PurchaseOrderDAO.getClientAddress().getAddressId() );
				setVendorNameAndShippingAddresses( purchaseOrderForm );
				purchaseOrderForm.setShippingMethodsList( NewCustomerDAO.loadAllShippingMethods ( null, -1 ) );
                purchaseOrderForm.setPayTermsList( SalesDAO.getAllShippingTerms() );
                request.setAttribute ( "financeReasonCodes", PurchaseOrderDAO.loadFinanceHolds() );
				request.setAttribute ( "opsReasonCodes", PurchaseOrderDAO.loadOperationsHolds() );
                setVendorSalesAddresses(purchaseOrderForm);
                actionForward = "openPurchaseOrder";
			}
		}
		catch ( Exception e )
		{
			Logger.error( "Error Loading New Open Purchase Order Screen", e );
			errors.put( ERROR_INTERNAL_SERVER_ERROR, "Error Loading New Open Purchase Order Screen" );
			mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while executing the command", e ) );
			actionForward = "search";
		}

		request.setAttribute( ERROR_MESSAGES, errors );
		request.setAttribute( INFO_MESSAGES, info );
		return mapping.findForward( actionForward );
	}

	/**
	 * @param
	 */
	private void setVendorNameAndShippingAddresses(OpenPurchaseOrderForm purchaseOrderForm ) throws ScalarException
	{
		Vendor vendor 	= VendorDAO.getVendorDetails( purchaseOrderForm.getVendor_id() );
		purchaseOrderForm.setVendorName( vendor.getVendorName() );

		ArrayList addressList = PurchaseOrderDAO.loadVendorShippingAddresses( purchaseOrderForm.getVendor_id() );
        ArrayList vendorAddessList =  new ArrayList();
        ArrayList contactPersonList = new ArrayList();
		Address address 	= null;
		LabelValueBean bean = null;

		for( int i = 0; i < addressList.size(); i++ )
		{
			address = (Address)addressList.get( i );

			if( "0".equalsIgnoreCase( address.getDefaultAddress() ) )
			{
				purchaseOrderForm.setShippingAddress( address );
				purchaseOrderForm.setShippingAddress_id( address.getAddressId() );

				if( address.getContactPersonAddressId() == -1 )
				{
					purchaseOrderForm.setContactPerson( address.getContactPerson() );
				}
				else
				{
					purchaseOrderForm.setContactPerson( "-1" );
				}
			}

			if( address.getContactPersonAddressId() == -1 )
			{
				bean = new LabelValueBean(  "-- Select --", "-1" );
			}
			else
			{
                if( "0".equalsIgnoreCase( address.getDefaultAddress() ) )
			    {
				    bean = new LabelValueBean( address.getContactPerson(), address.getContactPersonAddressId()+"" );
                    purchaseOrderForm.setContactPerson( address.getContactPersonAddressId()+"" );
                }
                else
                {
                    bean = new LabelValueBean( address.getContactPerson(), address.getContactPersonAddressId()+"" );
                }
			}
			contactPersonList.add( bean );
		}


		purchaseOrderForm.setShippingContactPersonList( contactPersonList );
		purchaseOrderForm.setShippingAddressList( addressList );

		if( purchaseOrderForm.getShippingAddress_id() == -1 )
		{
			purchaseOrderForm.setShippingAddress( ((Location)vendor.getLocationsList().get( 0 )).getLocationAddress() );
			purchaseOrderForm.setShippingAddress_id( ((Location)vendor.getLocationsList().get( 0 )).getLocationAddress().getAddressId() );
		}
	}

	/**
	 * @param purchaseOrderForm
	 */
	private void resetPurchaseOrderForm(OpenPurchaseOrderForm purchaseOrderForm)
	{
		purchaseOrderForm.setBillingAddress( null );
		purchaseOrderForm.setBillingAddress_id( -1 );
		purchaseOrderForm.setShippingAddress( null );
		purchaseOrderForm.setShippingAddress_id( -1 );

		purchaseOrderForm.setPurchaseOrder_id( -1 );
		purchaseOrderForm.setPoMaxAmt( "" );
        purchaseOrderForm.setPoIssuedAmt( "" );
		purchaseOrderForm.setVendorQuoteNumber( "" );
		purchaseOrderForm.setValidFromDate( "" );
		purchaseOrderForm.setValidToDate( "" );
		purchaseOrderForm.setFinanceHold( -1 );
		purchaseOrderForm.setOperationsHold( -1 );
		purchaseOrderForm.setComments( "" );

        purchaseOrderForm.setShippingMethodId( -1 );
        purchaseOrderForm.setShipMethod( null );
        purchaseOrderForm.setNewShippingAccount( "" );
        purchaseOrderForm.setNewShippingMethod( "" );
        purchaseOrderForm.setPayTerms( "" );
        purchaseOrderForm.setNewPayTerms( "" );
        purchaseOrderForm.setVendorAddressId("-1");
        purchaseOrderForm.setContactPerson("-1");
        
    }
    private void setVendorSalesAddresses(OpenPurchaseOrderForm purchaseOrderForm ) throws ScalarException
	{
		Vendor vendor 	= VendorDAO.getVendorDetails( purchaseOrderForm.getVendor_id() );
		ArrayList addressList = PurchaseOrderDAO.loadVendorSalesAddresses( purchaseOrderForm.getVendor_id() );
        ArrayList vendorAddessList =  new ArrayList();
        Address address 	= null;
		LabelValueBean bean = null;
        vendorAddessList.add( new LabelValueBean(  "-- Select --", "-1" ));
		for( int i = 0; i < addressList.size(); i++ )
		{
			    address = (Address)addressList.get( i );
                vendorAddessList.add(new LabelValueBean( address.getContactPerson(), address.getContactPersonAddressId()+"" ));
   		}
        purchaseOrderForm.setShippingVendorAddressList(addressList);
        purchaseOrderForm.setShippingVendorsList(vendorAddessList);
    }
}